package org.example.web.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class TestWebMvcConfigurer implements WebMvcConfigurer {
    Logger logger = LoggerFactory.getLogger(TestWebMvcConfigurer.class);

    @Override
    public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new HandlerExceptionResolver() {
            @Override
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) {
                String msg = ex.getMessage();
                logger.error(msg, ex);
                ModelAndView mav = new ModelAndView();
                MappingJackson2JsonView view = new MappingJackson2JsonView();
                view.setAttributesMap(convertToMap(msg));
                mav.setView(view);
                return mav;
            }

            private Map<String, Object> convertToMap(String msg) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("flag", 0);
                map.put("status", 400);
                map.put("msg", msg);
                return map;
            }
        });
    }
}
